package com.huan.es8.runtimefield;

import co.elastic.clients.elasticsearch._types.ScriptLanguage;
import co.elastic.clients.elasticsearch._types.mapping.RuntimeFieldType;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;

import java.io.IOException;

/**
 * 获取 runtime field 的值， runtime field不在_source中，需要通过 fields api来获取
 * @author huan.fu
 * @date 2023/2/1 - 23:01
 */
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class RetrieveRuntimeFieldValue extends AbstractRuntimeField{

    @Test
    @DisplayName("通过runtime field来进行搜索")
    public void test01() throws IOException {
        SearchRequest request = SearchRequest.of(searchRequest ->
                searchRequest.index(INDEX_NAME)
                        // runtime field字段不会出现在 _source中，需要使用使用 fields api来获取
                        .fields(fields -> fields.field("lineName"))
                        // 创建一个 runtime filed 字段类型是 keyword
                        .runtimeMappings("aggLineName", runtime ->
                                runtime
                                        // 此处给字段类型为keyword
                                        .type(RuntimeFieldType.Keyword)
                                        .script(script ->
                                                script.inline(inline ->
                                                        // runtime field中如果使用 painless脚本语言，需要使用emit
                                                        inline.lang(ScriptLanguage.Painless)
                                                                .source("emit(params['_source']['lineName']+'new')")
                                                )
                                        )
                        )
                        .query(query -> query.match(match -> match.field("aggLineName").query("线路Anew")))
                        .size(100)
        );

        System.out.println("request: " + request);
        SearchResponse<Object> response = client.search(request, Object.class);
        System.out.println("response: " + response);
    }

}
